package com.huluobo.lc.kotlinim1803a.contract.register

import android.util.Log
import cn.bmob.v3.BmobUser
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.SaveListener
import com.huluobo.lc.kotlinim1803a.extention.isValidPassword
import com.huluobo.lc.kotlinim1803a.extention.isValidUserName
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import kotlin.math.log

/**
 * @author Lc
 * @description:
 * @date :2020/9/14 15:21
 */
class RegisterPresenter(val view: RegisterContract.View) : RegisterContract.Presenter {
    override fun register(userName: String, password: String, confirmPassword: String) {
        if (userName.isValidUserName()) {
            //检查密码
            if (password.isValidPassword()) {
                //检查确认密码
                if (password == confirmPassword) {
                    //密码和确认密码一致
                    view.onStartRegister()
                    registerBmob(userName, password)

                } else view.onConfirmPasswordError()
            } else view.onPasswordError()
        } else view.onUserNameError()
    }

    private fun registerBmob(userName: String, password: String) {
        val bmobUser = BmobUser()
        bmobUser.username = userName
        bmobUser.setPassword(password)

        bmobUser.signUp(object : SaveListener<BmobUser>() {
            override fun done(bmobUser: BmobUser?, e: BmobException?) {
                if (e == null) {
                    //注册成功
                    //注册到环信,(公司流程)从服务器直接注册到环信,返回给app注册成功
                    registerEaseMob(userName, password)
                } else {
                    //注册Bmob失败
                    if (e.errorCode == 202) {
                        //用户名相同
                        runOnUIThread { view.onUserExist() }
                    } else {
                        runOnUIThread { view.onRegisterFailed("Bmob注册失败:" + e.errorCode.toString()) }
                    }
                }
            }
        })
    }

    private fun registerEaseMob(userName: String, password: String) {
        doAsync {//异步运行
            try {//使用try catch来返回成功或者失败
                EMClient.getInstance().createAccount(userName, password)//是同步方法
                //注册成功
                runOnUIThread { view.onRegisterSuccess() }

            } catch (e: HyphenateException) {
                //注册失败
                Log.i("TagA", "环信,E:$e")
                runOnUIThread { view.onRegisterFailed("环信注册失败:" + e.message.toString()) }
            }
        }
    }
}